<template>
  <div>
    <MyTable :list="list">
      <template #head>
        <th>#</th>
        <th>商品名称</th>
        <th>价格</th>
        <th>标签</th>
        <th>操作</th>
      </template>
      <template #body="{ row }">
        <td>{{ row.id }}</td>
        <td>{{ row.goods_name }}</td>
        <td>{{ row.goods_price }}</td>
        <td>
          <input
            class="tag-input form-control"
            style="width: 100px"
            type="text"
            v-if="row.inputVisible"
            v-fff
            @blur="row.inputVisible = false"
            v-model="row.inputValue"
            @keydown.esc="row.inputValue = ''"
            @keydown.enter="enterFn(row)"
          />
          <button
            v-else
            style="display: block"
            class="btn btn-primary btn-sm add-tag"
            @click="row.inputVisible = true"
          >
            +Tag
          </button>
          <span
            v-for="(str, index) in row.tags"
            :key="index"
            class="badge badge-warning"
            >{{ str }}</span
          >
        </td>
        <td>
          <!-- 自定义删除事件 -->
          <button class="btn btn-danger btn-sm" @click="delFn(row.id)">
            删除
          </button>
        </td>
      </template>
    </MyTable>
  </div>
</template>

<script>
import MyTable from "@/components/MyTable";
export default {
  data() {
    return {
      list: [],
    };
  },
  created() {
    // 可以在created中发起网络请求
    // console.log(this);
    this.$axios({
      url: "/api/goods",
    })
      .then((res) => {
        // console.log(res);
        this.list = res.data.data;
      })
      .catch((err) => console.log(err));
  },
  components: {
    MyTable,
  },
  methods: {
    delFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    enterFn(row) {
      // 做非空判断
      if (row.inputValue.trim() === "") return alert("输入不合法，请重新输入");
      // 将输入框输入的内容添加到tags数组
      row.tags.push(row.inputValue);
      row.inputValue = "";
    },
  },
  // 自定义指令
  directives: {
    fff: {
      // inserted函数当绑定元素el插入页面时触发一次
      inserted(el) {
        el.focus();
      },
    },
  },
};
</script>

<style>
</style>